using ComponentSystem;
using Cysharp.Threading.Tasks;
using UnityEngine;

namespace ZYFramework.AudioSystem
{
    /// <summary>
    /// 音频管理器实体
    /// </summary>
    public class AudioManager_Entity : EntityMono
    {
        /// <summary>
        /// 静态实例（全局访问）
        /// </summary>
        public static AudioManager_Entity Instance { get; private set; }

        /// <summary>
        /// 框架配置
        /// </summary>
        private AudioConfig _config;

        /// <summary>
        /// C#实体
        /// </summary>
        private AudioManagerEntityCSharp _entityCSharp;

        public void Initialization(AudioConfig config)
        {
            // 检查是否已存在实例
            if (Instance != null && Instance != this)
            {
                Debug.LogWarning("[AudioManagerEntity] 检测到多个AudioManagerEntity实例，将销毁重复实例");
                Destroy(gameObject);
                return;
            }

            // 设置静态实例
            Instance = this;
            UnityEngine.Object.DontDestroyOnLoad(gameObject);
            SetConfig(config);

            // 创建C#实体
            if (_entityCSharp == null)
            {
                _entityCSharp = this.AddCharpEntity<AudioManagerEntityCSharp>();
            }

            // 初始化C#实体
            if (_entityCSharp != null && _config != null)
            {
                _entityCSharp.Initialization(_config);
            }
            else
            {
                Debug.LogError("[AudioManagerEntity] 初始化失败：配置为空，请先调用 SetConfig() 设置配置");
            }

            base.Initialization();
        }

        /// <summary>
        /// 设置配置
        /// </summary>
        /// <param name="config">框架配置</param>
        public void SetConfig(AudioConfig config)
        {
            this._config = config;
        }

        /// <summary>
        /// LateUpdate：同步3D音效位置
        /// </summary>
        private void LateUpdate()
        {
            if (_entityCSharp != null)
            {
                _entityCSharp.Update3DPositions();
            }
        }

        protected override void OnDestroy()
        {
            // 清理C#实体（在Unity主线程上清理Unity对象）
            if (_entityCSharp != null)
            {
                // 确保对象池中的Unity对象在主线程上清理
                var sourcePool = _entityCSharp.GetComponent<Com_AudioSourcePool>();
                if (sourcePool != null)
                {
                    // 清理对象池（会清理所有Unity GameObject）
                    sourcePool.Clear();
                }

                _entityCSharp.Dispose();
                _entityCSharp = null;
            }

            base.OnDestroy();

            // 清理静态实例
            if (Instance == this)
            {
                Instance = null;
            }
        }

        #region 对外API（简化版，直接调用方式）

        /// <summary>
        /// 播放2D音效（简化API）
        /// </summary>
        public void PlaySFX(string audioName)
        {
            if (_entityCSharp != null)
            {
                _entityCSharp.PlaySFX2DAsync(audioName).Forget();
            }
        }

        /// <summary>
        /// 播放3D音效（简化API）
        /// </summary>
        public void Play3DSFX(string audioName, Transform bindTransform)
        {
            if (_entityCSharp != null)
            {
                _entityCSharp.PlaySFX3DAsync(audioName, bindTransform).Forget();
            }
        }

        /// <summary>
        /// 播放BGM（简化API）
        /// </summary>
        public void PlayBGM(string audioName)
        {
            if (_entityCSharp != null)
            {
                _entityCSharp.PlayBGMAsync(audioName).Forget();
            }
        }

        /// <summary>
        /// 停止所有SFX（简化API）
        /// </summary>
        public void StopAllSFX()
        {
            if (_entityCSharp != null)
            {
                _entityCSharp.StopAllAudio(AudioType.SFX_2D);
                _entityCSharp.StopAllAudio(AudioType.SFX_3D);
            }
        }

        #endregion

        #region 进阶API（异步方法）

        /// <summary>
        /// 播放2D音效（进阶API）
        /// </summary>
        public Cysharp.Threading.Tasks.UniTask PlaySFX2DAsync(string audioName, AudioPlayParams? param = null)
        {
            if (_entityCSharp != null)
            {
                return _entityCSharp.PlaySFX2DAsync(audioName, param);
            }
            return Cysharp.Threading.Tasks.UniTask.CompletedTask;
        }

        /// <summary>
        /// 播放3D音效（进阶API）
        /// </summary>
        public Cysharp.Threading.Tasks.UniTask PlaySFX3DAsync(string audioName, Transform bindTransform, AudioPlayParams? param = null)
        {
            if (_entityCSharp != null)
            {
                return _entityCSharp.PlaySFX3DAsync(audioName, bindTransform, param);
            }
            return Cysharp.Threading.Tasks.UniTask.CompletedTask;
        }

        /// <summary>
        /// 播放BGM（进阶API）
        /// </summary>
        public Cysharp.Threading.Tasks.UniTask PlayBGMAsync(string audioName, AudioPlayParams? param = null)
        {
            if (Instance == null)
            {
                Debug.LogError("[AudioManagerEntity] Instance为null，音频系统未初始化或已被销毁。请确保AudioManagerEntity已正确初始化。");
                return Cysharp.Threading.Tasks.UniTask.CompletedTask;
            }

            if (this != Instance)
            {
                Debug.LogWarning("[AudioManagerEntity] 当前实例不是全局Instance，使用全局Instance播放BGM");
                return Instance.PlayBGMAsync(audioName, param);
            }

            if (_entityCSharp != null)
            {
                return _entityCSharp.PlayBGMAsync(audioName, param);
            }

            Debug.LogError("[AudioManagerEntity] 内部实体未初始化，无法播放BGM");
            return Cysharp.Threading.Tasks.UniTask.CompletedTask;
        }

        /// <summary>
        /// 停止指定音效
        /// </summary>
        public void StopAudio(string audioName, AudioType audioType)
        {
            if (_entityCSharp != null)
            {
                _entityCSharp.StopAudio(audioName, audioType);
            }
        }

        /// <summary>
        /// 停止所有音效（按类型）
        /// </summary>
        public void StopAllAudio(AudioType? audioType = null)
        {
            if (_entityCSharp != null)
            {
                _entityCSharp.StopAllAudio(audioType);
            }
        }

        /// <summary>
        /// 设置全局音量
        /// </summary>
        public void SetGlobalVolume(AudioType audioType, float volume)
        {
            if (_entityCSharp != null)
            {
                _entityCSharp.SetGlobalVolume(audioType, volume);
            }
        }

        /// <summary>
        /// 静音/取消静音
        /// </summary>
        public void MuteAudio(AudioType audioType, bool isMute)
        {
            if (_entityCSharp != null)
            {
                _entityCSharp.MuteAudio(audioType, isMute);
            }
        }

        /// <summary>
        /// 预加载音效（支持单个/批量）
        /// </summary>
        public Cysharp.Threading.Tasks.UniTask<bool> PreloadAudioAsync(string audioName, AudioType audioType)
        {
            if (_entityCSharp != null)
            {
                return _entityCSharp.PreloadAudioAsync(audioName, audioType);
            }
            return Cysharp.Threading.Tasks.UniTask.FromResult(false);
        }

        /// <summary>
        /// 批量预加载音效
        /// </summary>
        public Cysharp.Threading.Tasks.UniTask<int> PreloadAudiosAsync(System.Collections.Generic.List<string> audioNames, AudioType audioType)
        {
            if (_entityCSharp != null)
            {
                return _entityCSharp.PreloadAudiosAsync(audioNames, audioType);
            }
            return Cysharp.Threading.Tasks.UniTask.FromResult(0);
        }

        /// <summary>
        /// 获取调试信息
        /// </summary>
        public string GetDebugInfo()
        {
            return _entityCSharp?.GetDebugInfo() ?? "调试信息不可用";
        }

        /// <summary>
        /// 获取当前播放的音效列表（调试用）
        /// </summary>
        public System.Collections.Generic.List<string> GetPlayingAudioList()
        {
            return _entityCSharp?.GetPlayingAudioList() ?? new System.Collections.Generic.List<string>();
        }

        /// <summary>
        /// 打印调试信息到控制台
        /// </summary>
        public void PrintDebugInfo()
        {
            _entityCSharp?.PrintDebugInfo();
        }

        #endregion
    }

    /// <summary>
    /// 音频管理器实体C#部分
    /// </summary>
    public class AudioManagerEntityCSharp : EntityCSharp
    {
        /// <summary>
        /// 资源管理组件
        /// </summary>
        private Com_AudioResourceManager _resourceManager;

        /// <summary>
        /// 对象池组件
        /// </summary>
        private Com_AudioSourcePool _sourcePool;

        /// <summary>
        /// 播放控制组件
        /// </summary>
        private Com_AudioPlayController _playController;

        /// <summary>
        /// 全局控制组件
        /// </summary>
        private Com_AudioGlobalControl _globalControl;

        /// <summary>
        /// 3D更新器组件
        /// </summary>
        private Com_Audio3DUpdater _3DUpdater;

        /// <summary>
        /// 调试监控组件
        /// </summary>
        private Com_AudioDebugMonitor _debugMonitor;

        /// <summary>
        /// 框架配置
        /// </summary>
        private AudioConfig _config;

        /// <summary>
        /// 父Mono实体
        /// </summary>
        private AudioManager_Entity _parentMono;

        /// <summary>
        /// 初始化音频管理器实体
        /// </summary>
        /// <param name="config">框架配置</param>
        public void Initialization(AudioConfig config)
        {
            this._config = config;

            // 获取父Mono实体
            _parentMono = this.GetParentMono<AudioManager_Entity>();

            // 添加组件
            AddComponents();

            // 初始化组件
            InitializeComponents();

            base.Initialization();
        }

        /// <summary>
        /// 添加组件
        /// </summary>
        private void AddComponents()
        {
            _resourceManager = this.AddComponent<Com_AudioResourceManager>();
            _sourcePool = this.AddComponent<Com_AudioSourcePool>();
            _playController = this.AddComponent<Com_AudioPlayController>();
            _globalControl = this.AddComponent<Com_AudioGlobalControl>();
            _3DUpdater = this.AddComponent<Com_Audio3DUpdater>();
            _debugMonitor = this.AddComponent<Com_AudioDebugMonitor>();
        }

        /// <summary>
        /// 初始化组件
        /// </summary>
        private void InitializeComponents()
        {
            // 初始化资源管理器
            _resourceManager.Initialize(_config);

            // 初始化对象池
            _sourcePool.Initialize(_config);

            // 初始化全局控制
            _globalControl.Initialize(_config);

            // 初始化3D更新器
            _3DUpdater.Initialize(_parentMono);

            // 初始化播放控制器
            _playController.Initialize(_resourceManager, _sourcePool, _3DUpdater, _globalControl, _config);

            // 初始化调试监控（默认启用调试模式）
            bool enableDebug = UnityEngine.Application.isEditor || UnityEngine.Debug.isDebugBuild;
            _debugMonitor.Initialize(_resourceManager, _sourcePool, _playController, _globalControl, enableDebug);
        }

        /// <summary>
        /// 更新3D音效位置（在LateUpdate中调用）
        /// </summary>
        public void Update3DPositions()
        {
            _3DUpdater?.Update3DPositions();
        }

        #region 对外API

        /// <summary>
        /// 播放2D音效
        /// </summary>
        public Cysharp.Threading.Tasks.UniTask PlaySFX2DAsync(string audioName, AudioPlayParams? param = null)
        {
            return _playController?.PlaySFX2DAsync(audioName, param) ?? Cysharp.Threading.Tasks.UniTask.CompletedTask;
        }

        /// <summary>
        /// 播放3D音效
        /// </summary>
        public Cysharp.Threading.Tasks.UniTask PlaySFX3DAsync(string audioName, Transform bindTransform, AudioPlayParams? param = null)
        {
            return _playController?.PlaySFX3DAsync(audioName, bindTransform, param) ?? Cysharp.Threading.Tasks.UniTask.CompletedTask;
        }

        /// <summary>
        /// 播放BGM
        /// </summary>
        public Cysharp.Threading.Tasks.UniTask PlayBGMAsync(string audioName, AudioPlayParams? param = null)
        {
            return _playController?.PlayBGMAsync(audioName, param) ?? Cysharp.Threading.Tasks.UniTask.CompletedTask;
        }

        /// <summary>
        /// 停止指定音效
        /// </summary>
        public void StopAudio(string audioName, AudioType audioType)
        {
            _playController?.StopAudio(audioName, audioType);
        }

        /// <summary>
        /// 停止所有音效（按类型）
        /// </summary>
        public void StopAllAudio(AudioType? audioType = null)
        {
            _playController?.StopAllAudio(audioType);
        }

        /// <summary>
        /// 设置全局音量
        /// </summary>
        public void SetGlobalVolume(AudioType audioType, float volume)
        {
            _globalControl?.SetGlobalVolume(audioType, volume);
        }

        /// <summary>
        /// 静音/取消静音
        /// </summary>
        public void MuteAudio(AudioType audioType, bool isMute)
        {
            _globalControl?.MuteAudio(audioType, isMute);
        }

        /// <summary>
        /// 预加载音效
        /// </summary>
        public Cysharp.Threading.Tasks.UniTask<bool> PreloadAudioAsync(string audioName, AudioType audioType)
        {
            return _resourceManager?.PreloadAudioAsync(audioName, audioType) ?? Cysharp.Threading.Tasks.UniTask.FromResult(false);
        }

        /// <summary>
        /// 批量预加载音效
        /// </summary>
        public Cysharp.Threading.Tasks.UniTask<int> PreloadAudiosAsync(System.Collections.Generic.List<string> audioNames, AudioType audioType)
        {
            return _resourceManager?.PreloadAudiosAsync(audioNames, audioType) ?? Cysharp.Threading.Tasks.UniTask.FromResult(0);
        }

        /// <summary>
        /// 获取调试信息
        /// </summary>
        public string GetDebugInfo()
        {
            return _debugMonitor?.GetDebugInfo() ?? "调试信息不可用";
        }

        /// <summary>
        /// 获取当前播放的音效列表（调试用）
        /// </summary>
        public System.Collections.Generic.List<string> GetPlayingAudioList()
        {
            return _debugMonitor?.GetPlayingAudioList() ?? new System.Collections.Generic.List<string>();
        }

        /// <summary>
        /// 打印调试信息到控制台
        /// </summary>
        public void PrintDebugInfo()
        {
            _debugMonitor?.PrintDebugInfo();
        }

        #endregion
    }
}
